package com.bigboss.knowstar.utils;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        String token = req.getHeader("Token");
        try {
            JWTUtil.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            map.put("data", "token已过期");
        } catch (SignatureVerificationException e) {
            map.put("data", "无效签名");
        } catch (Exception e) {
            map.put("data", "token无效");
        }
        map.put("status", "error");
        PrintWriter out = resp.getWriter();
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
        return false;
    }
}
